<template>
  <el-form :model="user" ref="login" :rules="rules">
    <el-form-item prop="userName" label="用户名">
      <el-input
        v-model="user.userName"
        placeholder="4-8为英文数字下划线组成,字母开头"
      ></el-input>
    </el-form-item>
    <el-form-item prop="pwd" label="密码">
      <el-input v-model="user.pwd" type="password" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="userLogin">登录</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { userLogin } from "@/api/user";
export default {
  name: "LoginPage",
  data() {
    return {
      rules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
          },
          {
            pattern: /^[a-zA-Z]\w{3,7}$/,
            message: "用户名格式不正确",
          },
        ],
        pwd: [
          {
            required: true,
            message: "请输入密码",
          },
          {
            pattern: /^[a-zA-Z]\w{3,7}$/,
            message: "密码格式不正确",
          },
        ],
      },
      user: {
        userName: "",
        pwd: "",
      },
    };
  },
  methods: {
    userLogin() {
      this.$refs.login
        .validate()
        .then(() => {
          userLogin(this.user).then((res) => {
            if (res.data.code === 200) {
              // 将返回的数据存储在 缓存中备份
              const { token, userInfo, role, btns } = res.data.data;
              localStorage.setItem("token", token);
              localStorage.setItem("userInfo", JSON.stringify(userInfo));
              localStorage.setItem("role", role);
              localStorage.setItem("btns", JSON.stringify(btns));
              // 存储到vuex中
              this.$store.commit("user/SET_USER", res.data.data);
              // 弹出成功提示 跳转到 主页
              this.$message({
                type: "success",
                duration: 1500,
                message: "登录成功",
                onClose: () => {
                  this.$router.replace("/dashBoard");
                },
              });
            }
          });
        })
        .catch(() => {
          this.$message.error("校验不通过");
        });
    },
    reset() {
      this.$refs.login.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped></style>
